package com.xing.user.api;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.xing.common.result.Result;
import com.xing.user.entity.UserInfo;
import com.xing.user.service.UserInfoService;
import com.xing.user.utils.ConstantWxPropertiesUtils;
import com.xing.user.utils.HttpClientUtils;
import com.xing.user.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 邢福豪
 * @date 2022/7/25 14:04
 */

//微信操作的接口
@Controller
@RequestMapping("/api/ucenter/wx")

public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;


    //1.生成微信扫描二维码    返回生成二维码需要的参数
    //这个地方是个坑，误人子弟
    //这块内容，实际操作，尽可能的粘贴复制，否则就是个bug,不好发现的
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getQrConnect(HttpSession session) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
        //redirect_uri 这个参数需要编码
        String redirectUri = URLEncoder.encode(ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL, "UTF-8");
        map.put("redirectUri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");
        return Result.ok(map);
    }


    //微信扫描后回调的方法
    @GetMapping("callback")
    public String callback(String code, String state) {
        //1.获取临时票据 code
        System.out.println("=========code:" + code);
        //2.拿着code和微信id和秘钥，请求微信固定地址，得到两个值
        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);

        //使用httpClient进行请求
        String accessTokenInfo = null;
        try {

            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("========访问token信息：" + accessTokenInfo);

            //从返回字符串获取 openid和access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //根据openid判断数据库是否存在微信信息
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);

            if (userInfo == null) {
                //3.拿着open_id和access_token 请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("==============resultInfo 请求结果信息" + resultInfo);

                //获取用户信息
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                String nickname = resultUserInfoJson.getString("nickname");
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //获取扫描人信息添加到数据库中
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                //保存到数据库
                userInfoService.save(userInfo);
            }

            Map<String, Object> map = new HashMap<>();
            String name = userInfo.getName();

            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }

            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }

            map.put("name", name);
            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openi值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }

            //使用jwt生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            //重定向到前端
            return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL
                    + "/weixin/callback?token=" + map.get("token")
                    + "&openid=" + map.get("openid") +
                    "&name=" + URLEncoder.encode((String) map.get("name"), "utf-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }




}
